//
//  QSEnterpriseVisitViewController.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/19.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSEnterpriseVisitViewController.h"
#import "QSVisitHeaderView.h"
#import "QSVisitScreeningView.h"
#import "QSVisitMessageCell.h"
#import "QSAddVisitViewController.h"
#import "QSVisitInterFace.h"
#import "BRPickerView.h"
#import "QSSingInInterface.h"
#import <SDAutoLayout.h>
#import "QSOtherSelectCompanyViewController.h"

#import "QSVisitItemView.h"
#import "QSEnterpriseSignInController.h"
#import "QSProblemSeportViewController.h"
#import "QSProblemProcessingViewController.h"
@interface QSEnterpriseVisitViewController ()<QSVisitScreeningHeaderViewDelegate,QSVisitItemViewDelegate, UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
/** 头部视图*/
@property (nonatomic, strong)QSVisitHeaderView *visitHeaderView;
/** item集合视图*/
@property (nonatomic, strong)QSVisitItemView *itemHeaderView;
/** 筛选视图*/
@property (nonatomic, strong)QSVisitScreeningView *visitScreeningView;

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, assign)NSInteger pageIndex;

@property (nonatomic, assign) NSInteger epId;
@property (nonatomic, assign) NSInteger egId;
@property (nonatomic, strong) NSString *companyName;

@property (nonatomic, strong) NSString *startTime;
@property (nonatomic, strong) NSString *endTime;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, copy) NSArray *companyArr;//供公司筛选的数组
@property (nonatomic, strong) NSArray *companyModelArr;//企业模型数组
@end

static NSString *visitMessageCell = @"visitMessageCell";
@implementation QSEnterpriseVisitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"企业走访";
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
//    [self getCompanyList];//获取绑定企业列表
    [self configHeaderView];
    [self configScreeningView];
    [self congfigTableView];
    if ([QSUserManager sharedQSUserManager].user.enterpriseLevel.integerValue != 4) {
        //领导4无新增走访
//        [self configBarbuttonItem];
    }
    [self addRefreshHeader];
    [self addRefreshFooter];
    WeakSelf(weakSelf);
    //选择组员/分组动作
    _visitHeaderView.visitHeaderViewDidFinishLoadOpenList = ^(QSVisitInfoGroupListModel * _Nonnull model) {
        if (kCurrentUser.enterpriseLevel.intValue == 2) {
            //组长取epid（人）赋值
            if (model.epId) {
                NSLog(@"%@", model.epId);
                weakSelf.epId = model.epId.integerValue;
                [weakSelf getCompanyListWithEgId:model.egId EpId:model.epId];//根据人员id取关联企业列表
            }
        }
        if (kCurrentUser.enterpriseLevel.integerValue == 3 || kCurrentUser.enterpriseLevel.integerValue == 4) {
            //领导取egid(组)赋值
            if (model.egId) {
                weakSelf.egId = model.egId.integerValue;
                [weakSelf getCompanyListWithEgId:model.egId EpId:model.epId];//根据组id取关联企业列表
            }
        }
    };
    //加载公司列表回调 传回数组和自己的组id/组员id用作默认列表
    _visitHeaderView.visitHeaderViewDidLoadFinishCompanyArray = ^(NSArray * _Nonnull companyArr, NSString * _Nonnull egId, NSString * _Nonnull epId) {
//        weakSelf.companyArr = companyArr.copy;
//        NSLog(@"%ld", weakSelf.companyArr.count);
        if (kCurrentUser.enterpriseLevel.intValue == 2) {
            weakSelf.egId = egId.integerValue;
        }
        if (kCurrentUser.enterpriseLevel.integerValue == 1) {
            weakSelf.epId = epId.integerValue;
        }
        [weakSelf getCompanyListWithEgId:egId EpId:epId];//根据当前人id取关联企业列表
        [weakSelf startRefreshing];
    };
}

- (void)configHeaderView{
    [self.view addSubview:self.visitHeaderView];    
    [_visitHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kRealValue(10));
        make.right.equalTo(self.view).offset(- kRealValue(10));
        make.top.equalTo(self.view).offset(10);
        make.height.offset(kRealValue(150));
    }];
    
    [self.view addSubview:self.itemHeaderView];
    [_itemHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kRealValue(10));
        make.right.equalTo(self.view).offset(- kRealValue(10));
        make.top.equalTo(self.visitHeaderView.mas_bottom).offset(-5);
        make.height.offset(kRealValue(73));
    }];
}

- (void)configScreeningView{
    [self.view addSubview:self.visitScreeningView];
    [_visitScreeningView mas_makeConstraints:^(MASConstraintMaker *make) {
           make.left.equalTo(self.view).offset(kRealValue(10));
           make.right.equalTo(self.view).offset(- kRealValue(10));
           make.top.equalTo(self.itemHeaderView.mas_bottom).offset(10);
           make.height.offset(kRealValue(40));
       }];
}

- (void)congfigTableView{
    [self.view addSubview:self.tableView];
}

- (void)configBarbuttonItem{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"新增走访" style:UIBarButtonItemStyleDone target:self action:@selector(addVisitAction:)];
}

-(QSVisitHeaderView *)visitHeaderView{
    if (!_visitHeaderView) {
        _visitHeaderView = [[QSVisitHeaderView alloc]init];
        _visitHeaderView.layer.cornerRadius = 5;
        _visitHeaderView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
    }
    return _visitHeaderView;
}

- (QSVisitItemView *)itemHeaderView{
    if (!_itemHeaderView) {
        _itemHeaderView = [[QSVisitItemView alloc]init];
        _itemHeaderView.layer.cornerRadius = 5;
        _itemHeaderView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
        _itemHeaderView.delegate = self;
    }
    return _itemHeaderView;
}

- (QSVisitScreeningView *)visitScreeningView{
    if (!_visitScreeningView) {
        _visitScreeningView = [[QSVisitScreeningView alloc]init];
        _visitScreeningView.layer.cornerRadius = 5;
        _visitScreeningView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
        _visitScreeningView.delegate = self;
    }
    return _visitScreeningView;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    if (!_tableView) {
        CGFloat tableViewY = kRealValue(150) + kRealValue(73) + kRealValue(40) + kRealValue(30 - 5) ;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(10, tableViewY, kScreenWidth - kRealValue(20), kScreenHeight - tableViewY - kNavgationBarHeight - kTabBarHeight) style:UITableViewStylePlain];
        _tableView.layer.cornerRadius = 5;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"QSVisitMessageCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:visitMessageCell];
    }
    return _tableView;
}
#pragma mark - Api - 获取绑定企业列表
- (void)getCompanyListWithPageIndex:(NSInteger)pageIndex{
    
    [QSAppKeyWindow showIndeterminateHudWithText:@"加载中"];
    [QSSingInInterface getShowAllCompanyAndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSString * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            [self getCompanyWithEpAllCompany:result pageIndex:pageIndex];
        }
    }];
}

- (void)getCompanyWithEpAllCompany:(NSString *)epAllCompany pageIndex:(NSInteger)pageIndex{
    [QSAppKeyWindow showIndeterminateHudWithText:@"加载中"];
    [QSSingInInterface getCompanyListWithPageIndex:pageIndex EpAllCompany:epAllCompany andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSBindingEnterprisesModel * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            self.companyModelArr = result;
            NSLog(@"%@", result);
        }
    }];
}



#pragma mark - QSVisitScreeningHeaderViewDelegate
//点击清除筛选
-(void)visitScreeningView:(QSVisitScreeningView *)headerView didSelectSearchButton:(UIButton *)sender{
//    [QSAppKeyWindow showAutoHideHudWithText:@"清除筛选"];
    self.companyName = nil;
    self.startTime = nil;
    self.endTime = nil;
    [headerView.timeScreenButton setTitle:@"时间筛选" forState:UIControlStateNormal];
    headerView.timeScreenButton.titleLabel.font = [UIFont QSFontOfSize14];
    [headerView.timeScreenButton setImage:[UIImage imageNamed:@"ic_selectpeople"] forState:UIControlStateNormal];

    headerView.enterpriseScreenButton.titleLabel.font = [UIFont QSFontOfSize14];
    [headerView.enterpriseScreenButton setTitle:@"企业筛选" forState:UIControlStateNormal];
    [headerView.enterpriseScreenButton setImage:[UIImage imageNamed:@"ic_selectpeople"] forState:UIControlStateNormal];
    [self tableViewShouldUpdateDataByPageIndex:1];
}


//点击选择公司
- (void)visitScreeningView:(QSVisitScreeningView *)headerView didSelectEnterpriseScreenButton:(UIButton *)sender{
    QSOtherSelectCompanyViewController *vc = [QSOtherSelectCompanyViewController new];
    vc.didSelectCompanyBlock = ^(QSVisitInfoCompanyListModel *model) {
        self.companyName = model.companyName;//选中key
        self.visitScreeningView.enterpriseScreenButton.titleLabel.numberOfLines = 2;
        self.visitScreeningView.enterpriseScreenButton.imageView.hidden = YES;
        self.visitScreeningView.enterpriseScreenButton.titleLabel.font = [UIFont QSFontOfSize10];
        [self.visitScreeningView.enterpriseScreenButton setTitle:model.companyName forState:UIControlStateNormal];
        [self.visitScreeningView.enterpriseScreenButton setImage:nil forState:UIControlStateNormal];
        [self tableViewShouldUpdateDataByPageIndex:1];
    };
    [self.navigationController pushViewController:vc animated:YES];
//    if (self.companyArr.count) {
//        NSMutableArray *copyCompanyArr = [NSMutableArray array];
//        for (QSVisitInfoCompanyListModel *model in self.companyArr) {
//            NSString *companyName = model.companyName;
//            [copyCompanyArr addObject:companyName];
//        }
//        [BRStringPickerView showStringPickerWithTitle:@"请选择公司" dataSource:copyCompanyArr defaultSelValue:nil resultBlock:^(id selectValue) {
//            for (QSVisitInfoCompanyListModel *model in self.companyArr) {
//                if ([model.companyName isEqualToString:selectValue]) {
//                    //取出选中公司key赋值
//                    self.companyName = model.companyName;
//                    break;
//                }
//            }
//            self.visitScreeningView.enterpriseScreenButton.titleLabel.numberOfLines = 2;
//            self.visitScreeningView.enterpriseScreenButton.imageView.hidden = YES;
//            self.visitScreeningView.enterpriseScreenButton.titleLabel.font = [UIFont QSFontOfSize10];
//            [self.visitScreeningView.enterpriseScreenButton setTitle:selectValue forState:UIControlStateNormal];
//            [self tableViewShouldUpdateDataByPageIndex:1];
//        }];
//    }else{
//        [QSAppKeyWindow showAutoHideHudWithText:@"当前组无绑定公司!"];
//    }
    
}
//选择时间
- (void)visitScreeningView:(QSVisitScreeningView *)headerView didSelectTimeScreenButton:(UIButton *)sender{
    [BRDatePickerView showDatePickerWithTitle:@"请选择开始日期" dateType:BRDatePickerModeYMD defaultSelValue:nil resultBlock:^(NSDate *selectDate, NSString *selectValue) {
        NSTimeInterval stamp = [selectDate timeIntervalSince1970];
        self.startTime = [NSString stringWithFormat:@"%.0f", stamp *1000];
        NSString *startStr = selectValue;
        [BRDatePickerView showDatePickerWithTitle:@"请选择结束日期" dateType:BRDatePickerModeYMD defaultSelValue:nil resultBlock:^(NSDate *selectDate, NSString *selectValue) {
            
            NSTimeInterval stamp = [selectDate timeIntervalSince1970];
            self.endTime = [NSString stringWithFormat:@"%.0f", stamp *1000];
            if (self.startTime.doubleValue > self.endTime.doubleValue) {
                [QSAppKeyWindow showAutoHideHudWithText:@"起始时间不能大于终止时间!"];
                self.startTime = nil;
                self.endTime = nil;
                [headerView.timeScreenButton setTitle:@"时间筛选" forState:UIControlStateNormal];
                return ;
            }
            headerView.timeScreenButton.titleLabel.numberOfLines = 2;
            headerView.timeScreenButton.imageView.hidden = YES;
            [headerView.timeScreenButton setTitle:[NSString stringWithFormat:@"%@ -\n %@", startStr, selectValue] forState:UIControlStateNormal];
            [headerView.timeScreenButton setImage:nil forState:UIControlStateNormal];

            [headerView.timeScreenButton.titleLabel setFont:[UIFont QSFontOfSize11]];
            [self tableViewShouldUpdateDataByPageIndex:1];
        }];
    }];
}

#pragma mark  - QSVisitItemViewDelegate
- (void)visitItemView:(QSVisitItemView *)itemView navigationCollectionViewdidSelectItemAtIndexPath:(NSIndexPath *)indexPath itemModel:(QSItemModel *)itemModel{
    if ([itemModel.label isEqualToString:@"新增走访"]) {
        [self addVisitAction:nil];
    }
    if ([itemModel.label isEqualToString:@"领导驾驶舱"]) {
        
    }
    if ([itemModel.label isEqualToString:@"一企一档"]) {
        
    }
    if ([itemModel.label isEqualToString:@"驻企签到"]) {
        QSEnterpriseSignInController *vc = [QSEnterpriseSignInController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([itemModel.label isEqualToString:@"企业走访"]) {

    }
    if ([itemModel.label isEqualToString:@"问题处理"]) {
        QSProblemProcessingViewController *vc = [QSProblemProcessingViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([itemModel.label isEqualToString:@"问题上报"]) {
        QSProblemSeportViewController *vc = [QSProblemSeportViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    //新增
    if ([itemModel.label isEqualToString:@"政策宝典"]) {
        
    }
    if ([itemModel.label isEqualToString:@"企业运行监测"]) {
        
    }
}

#pragma mark - **************** UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    QSVisitMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:visitMessageCell];
    NSString*cellID = [NSString stringWithFormat:@"%zd",indexPath.row];
    QSVisitMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    // 判断为空进行初始化  --（当拉动页面显示超过主页面内容的时候就会重用之前的cell，而不会再次初始化）
    if (!cell) {
        cell = (QSVisitMessageCell *)[[[NSBundle  mainBundle]  loadNibNamed:@"QSVisitMessageCell" owner:self options:nil]  objectAtIndex:0];
        [cell setValue:cellID forKey:@"reuseIdentifier"];
    }
    cell.model = _dataArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.didOpenTheProblemListBlock = ^(UIButton * _Nonnull openButton, CGFloat tabelViewH) {
        [self.tableView reloadData];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    QSVisitDetailModel *model = self.dataArray[indexPath.row];
    return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[QSVisitMessageCell class] contentViewWidth:kScreenWidth - 20] + model.tableH;
//    return kRealValue(304 + 10);//cell间距
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
}

#pragma mark - Action
- (void)addVisitAction:(UIBarButtonItem *)sender{
    QSAddVisitViewController *vc = [QSAddVisitViewController new];
    vc.companyModelList = self.companyModelArr;
    NSLog(@"%@", vc.companyModelList);
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)addRefreshHeader {
    WeakSelf(weakSelf);
    [self.tableView addRefreshHeaderWithRefreshingBlock:^{
        weakSelf.pageIndex = 1;
        [weakSelf tableViewShouldUpdateDataByPageIndex:weakSelf.pageIndex];
    }];
}

- (void)addRefreshFooter {
    WeakSelf(weakSelf);
    [self.tableView addRefreshFooterWithRefreshingBlock:^{
        weakSelf.pageIndex ++;
        [weakSelf tableViewShouldUpdateDataByPageIndex:weakSelf.pageIndex];
    }];
}

- (void)startRefreshing {
    [self startRefreshing:NO];
}

- (void)startRefreshing:(BOOL)animated {
    self.pageIndex = 1;
    if (animated) {
        [self.tableView qs_startRefreshing];
    } else {
        [self tableViewShouldUpdateDataByPageIndex:self.pageIndex];
    }
}


- (void)tableViewShouldUpdateDataByPageIndex:(NSInteger)pageIndex {
    [QSAppKeyWindow showIndeterminateHudWithText:@"加载中"];
    NSLog(@"%ld  -- %ld", _epId, _egId);
    [QSVisitInterFace getVisitListWithPageIndex:pageIndex Level:kCurrentUser.enterpriseLevel.intValue Epid:_epId Egid:_egId CompanyName:_companyName StartTime:_startTime EndTime:_endTime AndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSVisitHomeListModel * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            if (pageIndex == 1) {
                [self.dataArray removeAllObjects];
            }
            [self.dataArray addObjectsFromArray:result.list];
            self.tableView.emptyDataSetSource = self;
            self.tableView.emptyDataSetDelegate = self;
            [self.tableView reloadData];
            [self.tableView qs_endRefreshing];
            if (pageIndex >= result.pages) {
//                self.tableView.mj_footer.hidden = YES;
                [self.tableView qs_endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
            }
        }
    }];
}

//根据切换的组/组员 获取公司列表
- (void)getCompanyListWithEgId:(NSString *)egId
                          EpId:(NSString *)epId{
    [QSVisitInterFace getVisitCompanysWithEpId:epId EgId:egId AndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSArray * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            self.companyArr = result;
            [self tableViewShouldUpdateDataByPageIndex:1];//获取企业后重新获取数据
        }
    }];

}

#pragma mark - DZNEmptyDataSetSource
/**
 *  返回标题文字
 */
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"暂无走访信息";
    NSDictionary *attributes = @{ NSFontAttributeName: [UIFont boldSystemFontOfSize:14.0f],
                                     NSForegroundColorAttributeName: [UIColor QSColorBlack666666] };
    return [[NSAttributedString alloc]initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    scrollView.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    return [UIImage imageNamed:@"ic_problem_null"];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
